package org.tourism.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Calendar;

public class JWTUtils {
    public static final String secret="tourism";

    /**
     * 生成token
     * @param id
     * @return
     */
    public static String generateToken(int id){
        Calendar instance=Calendar.getInstance();
        //有限期一天
        instance.add(Calendar.DATE,1);
        return JWT.create().withClaim("id",id).withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(secret));
    }

    /**
     * 先从request的header中取出token，再对token进行解码，获取用户的id,返回int类型的id
     * @param httpServletRequest
     * @return
     */
    public static int decodeToken(HttpServletRequest httpServletRequest){
        String token=httpServletRequest.getHeader("token");
        DecodedJWT result=JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return result.getClaim("id").asInt();
    }

    /**
     * 重载，直接传入token，对token进行解码，返回int类型的id
     * @param token
     * @return
     */
    public static int decodeToken(String token){
        DecodedJWT result=JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return result.getClaim("uid").asInt();
    }
}
